package optimizers.ganeat.report;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;

import optimizers.commons.RunConfig;
import optimizers.ganeat.Constants;
import optimizers.ganeat.Individual;
import optimizers.ganeat.Species;

public class LoggerNEAT {
	private String filename;
	private boolean showInConsole;
	public ArrayList<ArrayList<Species>> speciesVisualData;
	public Map<String, Integer> innovations;
	public Map<String, String> nodeNames;
	public ArrayList<Individual> speciesLib;
	public RunConfig config;
	public StringBuilder builder;
	double[][] speciesData = new double[1][Constants.generations + 1];

	public LoggerNEAT(String filename, boolean showInConsole,
			ArrayList<ArrayList<Species>> speciesVisualData,
			double[][] speciesData, Map<String, Integer> innovations,
			Map<String, String> nodeNames, ArrayList<Individual> speciesLib,
			RunConfig config) {
		System.out.println(filename);
		this.filename = filename;
		this.showInConsole = showInConsole;
		this.speciesVisualData = speciesVisualData;
		this.speciesData = speciesData;
		this.builder = new StringBuilder();
		this.innovations = innovations;
		this.nodeNames = nodeNames;
		this.speciesLib = speciesLib;
		this.config = config;
	}

	public void logToMemory(String message) {
		builder.append(message + "\r\n");
		if (showInConsole) {
			System.out.println(message);
		}
	}

	public void saveToFile() {
		FileOutputStream saveFile = null;
		do {
			try {
				saveFile = new FileOutputStream(filename);
				ObjectOutputStream save = new ObjectOutputStream(saveFile);
				save.writeObject(speciesVisualData);
				save.writeObject(speciesData);
				save.writeObject(innovations);
				save.writeObject(nodeNames);
				save.writeObject(speciesLib);
				save.writeObject(config);
				save.close();
				saveFile.close();
				PrintWriter out = new PrintWriter(filename + ".txt");
				out.println(builder.toString());
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} while (saveFile == null);
	}
}
